<?php
/**
 * Created by PhpStorm.
 * User: jaylen
 * Date: 2020-04-12
 * Time: 11:51
 */

namespace app\admin\middleware;

use app\admin\model\Admin;
use app\common\exception\NoRuleException;
use app\common\exception\TokenException;
use app\admin\model\AuthRule as AuthRuleModel;


class RoleCheck
{
    public function handle($request, \Closure $next)
    {

        // 验证token是否有效，并获取对应的信息
        $token_data = Admin::getCurrentUser();

        // 添加token_data到请求中
        $request->token_data = $token_data;

        // 判断权限开关是否已经打开
        $auth_on = get_system_config('bk_auth_on');
        if ($auth_on === '关闭') {
            return $next($request);
        }

        // 定义方法白名单
        $allow = [
            'index/index',  // 首页
        ];

        // 查询所有权限白名单
        $public_rule = AuthRuleModel::where('public_rule','=', 1)
            ->field('name')
            ->select();

        $public_rule = !empty($public_rule) ? $public_rule->toArray() : [];

        // 拼接白名单数组
        $allow = array_merge($allow, $public_rule);

        // 查找当前控制器和方法，控制器和方法都是小写
        $ctr_name = $request->controller(true);
        $act_name = $request->action(true);
        if (empty($ctr_name) || empty($act_name)) {
            $route = $request->rule()->getRoute();
            $route_name = str_replace(['\\','@'],'/',$route);
            // 转换为小写
            $route_name = strtolower($route_name);
        } else {
            $route_name = $ctr_name . '/' . $act_name;
        }

        // 权限验证
        if (!in_array($route_name, $allow)) {
            if (!auth_check($route_name, $token_data['uid'])) {
                throw new NoRuleException();
            }
        }



        return $next($request);
    }
}